package stat

import (
	"errors"

	"gddgame.cc/galaxy/binocle"
	"gddgame.cc/galaxy/common/dsl/game"
	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/utils"
)

const providerName = "stat"

func init() {
	_ = game.RegisterGlobalModule(game.ModuleProvider{
		Name: providerName,

		OnInit: func(env *game.Environment) error {
			var err error
			if _, err = env.RegisterModel(SettingStatName, &SettingStat{}); err != nil {
				return err
			}
			if _, err = env.RegisterModel(StatItemName, &StatItem{}); err != nil {
				return err
			}

			return nil
		},
		OnApp: func(app binocle.App, env *game.Environment) error {
			app.Schedule("CleanStat", func(args []string) error {
				if len(args) == 0 {
					return errors.New("args is empty")
				}
				v := args[0]
				switch v {
				case "daily":
					return CleanStatDaily(env)
				case "weekly":
					return CleanStatWeekly(env)
				case "monthly":
					return CleanStatMonthly(env)
				}
				return errors.New("arg in daily, weekly, monthly")
			})
			return nil
		},
	})
}

func CleanStatDaily(env *game.Environment) error {
	model, err := env.GetModel(StatItemName)
	if err != nil {
		return err
	}
	if _, err := model.Query().Where("=", "cycle", utils.DailyCycle).Delete(); err != nil {
		return SystemExceptionDetail("清理每天统计失败", err)
	}
	return nil
}

func CleanStatWeekly(env *game.Environment) error {
	model, err := env.GetModel(StatItemName)
	if err != nil {
		return err
	}
	if _, err := model.Query().Where("=", "cycle", utils.WeeklyCycle).Delete(); err != nil {
		return SystemExceptionDetail("清理每周统计失败", err)
	}
	return nil
}

func CleanStatMonthly(env *game.Environment) error {
	model, err := env.GetModel(StatItemName)
	if err != nil {
		return err
	}
	if _, err := model.Query().Where("=", "cycle", utils.MonthlyCycle).Delete(); err != nil {
		return SystemExceptionDetail("清理每月统计失败", err)
	}
	return nil
}
